<template>
  <PlatformDropdown @platformChange="platformChange">
    <div class="menu-container">
      <div v-loading="loading" class="menu-edited-container">
        <div class="menu-left-tree">
          <div class="menu-left-tools">
            <svg-icon class="tree-menu-tools" icon-class="tianjia2" @click="addNode" />
          </div>
          <div class="menu-left-container">
            <el-tree
              ref="menuLeftTree"
              :data="treeDatas"
              :props="defaultProps"
              node-key="treeIndex"
              default-expand-all
              :expand-on-click-node="false"
              draggable
              :highlight-current="true"
              :allow-drag="allowDrag"
              @node-click="editedNode"
            >
              <template #default="{ node }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span>
                    <svg-icon class="tree-node-tools" icon-class="tianjia1" @click="appendNode(node)" />
                    <el-popconfirm
                      confirm-button-text="确认"
                      cancel-button-text="不用了"
                      icon="el-icon-info"
                      icon-color="red"
                      title="确定删除吗？"
                      @onConfirm="removeNode(node)"
                    >
                      <svg-icon slot="reference" class="tree-node-tools" icon-class="shanchu1" />
                    </el-popconfirm>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
        <div class="menu-right-form">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="路由">
              <el-input v-model="form.routeKey" />
            </el-form-item>
            <el-form-item label="菜单名称">
              <el-input v-model="form.title" />
            </el-form-item>
          </el-form>
          <el-divider>元数据</el-divider>
          <component :is="formName" v-model="form.meta" />
        </div>
      </div>
      <div class="menu-btn-container">
        <div class="btn-group">
          <el-button type="success" :disabled="loading" @click="refreshTree">刷新</el-button>
          <el-button type="danger" :disabled="loading" @click="syncTree">同步</el-button>
        </div>
      </div>
      <el-dialog title="选择图标" :visible.sync="dialogVisible" width="30%">
        <div class="dialog-container">
          <svg-icon v-for="icon in icons" :key="'dialog-item-' + icon" class="dialog-item-icon" :icon-class="icon" @click="selectIcon(icon)" />
        </div>
      </el-dialog>
    </div>
  </PlatformDropdown>
</template>
<script>
import { tree, sync } from '@/api/menu.js'
import { keyRoutes } from '@/router'
import PlatformDropdown from '@/components/PlatformDropdown/index.vue'
import ManagerSystemForm from './components/ManagerSystemForm.vue'
import H5Form from './components/H5Form.vue'
import AppAndroidForm from './components/AppAndroidForm.vue'
import AppIosForm from './components/AppIosForm.vue'
import WeixinMiniForm from './components/WeixinMiniForm.vue'

let id = 1000

export default {
  name: `menu-manager`,
  components: { PlatformDropdown, ManagerSystemForm, H5Form, AppAndroidForm, AppIosForm, WeixinMiniForm },
  data() {
    return {
      formName: null,
      componentKeys: Object.keys(keyRoutes),
      icons: [],
      dialogVisible: false,
      loading: false,
      form: {},
      treeDatas: null,
      defaultProps: {
        children: 'childrens',
        label: 'title'
      },
      platformCode: null
    }
  },
  async mounted() {
    const idList = []
    document.querySelectorAll('body>svg symbol').forEach(item => idList.push(item.id.replace('icon-', '')))
    this.icons = idList.filter(item => !!item)
  },
  methods: {
    platformChange(platformCode) {
      switch (platformCode) {
        case 'MANAGER-SYSTEM':
          this.formName = 'ManagerSystemForm'
          break
        case 'H5':
          this.formName = 'H5Form'
          break
        case 'APP-ANDROID':
          this.formName = 'AppAndroidForm'
          break
        case 'APP-IOS':
          this.formName = 'AppIosForm'
          break
        case 'WEIXIN-MINI':
          this.formName = 'WeixinMiniForm'
          break
        default: this.formName = null
          break
      }
      this.platformCode = platformCode
      this.refreshTree()
    },
    showDialog() {
      this.dialogVisible = true
    },
    selectIcon(icon) {
      this.form.icon = icon
      this.dialogVisible = false
    },
    refreshTree() {
      this.treeDatas = []
      this.form = {}
      return tree({ platformCode: this.platformCode }).then(rsp => {
        if (rsp && rsp.code === 200) {
          this.treeDatas = rsp.data || []
          this.loading = false
          const node = this.treeDatas[0]
          if (node) {
            this.$nextTick(() => {
              this.$refs['menuLeftTree'].setCurrentKey(node.treeIndex)
              this.editedNode(node)
            })
          }
        } else {
          this.loading = false
          this.$message.error('刷新失败')
        }
      }).catch(e => {
        this.loading = false
        this.$message.error('刷新失败')
        console.error('刷新失败', e)
      })
    },
    syncTree() {
      this.loading = true
      sync(this.treeDatas, { platformCode: this.platformCode }).then(rsp => {
        if (rsp.data) {
          this.refreshTree()
        } else {
          this.loading = false
          this.$message.error('同步失败')
        }
      }).catch(e => {
        this.loading = false
        this.$message.error('同步失败')
        console.error('同步失败', e)
      })
    },
    allowDrag() {
      return true
    },
    appendNode(node) {
      const newChild = { id: id++, platformCode: this.platformCode, routeKey: '/', componentKey: 'main-view', title: '新建菜单', icon: 'default', cache: true, affix: false, breadcrumb: true, children: [] }
      if (!node.data.childrens) {
        node.data.childrens = []
      }
      node.data.childrens.push(newChild)
      this.treeDatas = [...this.treeDatas]
    },
    addNode() {
      const newChild = { id: id++, platformCode: this.platformCode, routeKey: '/', componentKey: 'layout', title: '新建菜单', icon: 'default', cache: true, affix: false, breadcrumb: true, children: [] }
      this.treeDatas = [...this.treeDatas, newChild]
    },
    editedNode(data, node, nodeEl) {
      this.form = data || node.data
      // this.form.meta = JSON.stringify(data || node.data)
    },
    removeNode(node) {
      console.log(node)
      const parent = node.parent
      const brothers = parent.data.childrens || parent.data
      const index = brothers.findIndex((d) => {
        return d.id === node.data.id
      })
      brothers.splice(index, 1)
      this.treeDatas = [...this.treeDatas]
    }
  }
}
</script>

<style lang="scss">
.menu-container{
  display: flex;
  width: 100%;
  height: 100%;
  position: absolute;
  flex-wrap: nowrap;
  flex-direction: column;
  .menu-edited-container{
    display: flex;
    overflow: hidden;
    flex-wrap: nowrap;
    height: 100%;
    .menu-left-tree{
      padding: 30px 0 0 20px;
      width: 300px;
      height: 100%;
      overflow: hidden;
      position: relative;
      .menu-left-tools{
        position: absolute;
        top: 0px;
        left: 0;
        font-size: 18px;
        width: 100%;
        padding: 0 10px;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        box-shadow: 0 1px 4px rgb(126 126 126 / 15%);
        height: 26px;
        align-items: center;
        .tree-menu-tools {
          margin: 0 4px;
          cursor: pointer;
        }
      }
      .menu-left-container{
        height: 100%;
        width: 100%;
        overflow: scroll;
        position: relative;
        &::-webkit-scrollbar {
          width: 7px;
          height: 8px;
        }
        &::-webkit-scrollbar-thumb {
          background-color: rgba(144,147,153,.3);
          border-radius: 2px;
          box-shadow: inset 0 0 6px rgb(0 0 0 / 20%);
        }
        &::-webkit-scrollbar-track {
          background-color: rgba(0,0,0,.05);
        }
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          .tree-node-tools {
            margin: 0 3px;
          }
        }
      }
    }
    .menu-right-form{
      padding: 20px;
      .el-form{
        width: 600px;
          .el-form-item__content{
            .el-select.el-select--medium{
              width: 100%;
            }
            .el-cascader.el-cascader--medium{
              width: 100%;
            }
          }
      }
    }
  }
  .menu-btn-container{
    flex-grow: 1;
    padding: 10px;
    position: relative;
    height: 70px;
    box-shadow: 0 -1px 4px rgb(0 17 32 / 15%);
    .btn-group{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      .el-button{
        margin: 0 40px;
      }
    }
  }

  .dialog-container{
    width: 500px;
    overflow: scroll;
    height: 500px;
    font-size: 15px;
    background-color: white;
    margin-right: 0;
    width: 100%;
    &::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: rgba(144,147,153,.3);
      border-radius: 0px;
      box-shadow: inset 0 0 6px rgb(0 0 0 / 20%);
    }
    &::-webkit-scrollbar-track {
      background-color: rgba(0,0,0,.05);
    }
    .dialog-item-icon{
      margin: 10px;
      cursor: pointer;
    }
  }
}
</style>
